package keyboard.controller.api;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import keyboaUtil.commonUtil.string.StringUtil;
import keyboaUtil.commonUtil.web.WebUtils;
import keyboaUtil.userData.MyCookie;
import keyboard.entity.Notes;
import keyboard.exception.ClientException;
import keyboard.service.NotesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import commonUtil.excption.WebResult;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author 2B键盘
 * @version 1.0
 * @create: 2018-05-04 0:05
 * @desc
 **/
@Controller
@RequestMapping("/notesApi")
public class NoteAPI {

    @Autowired
    NotesService notesService;

    /**
     * 添加新文章接口
     * @param request
     * @return
     */
    @RequestMapping("/notes.do")
    @ResponseBody
    public WebResult saveNote(HttpServletRequest request){
        String notes = request.getParameter("note");
        String title = request.getParameter("title");
        String identity = request.getParameter("identity");
        if(!StringUtil.isStringNotNull(notes)){
            return WebResult.fail("文章内容不能为空哦!");
        }
        if(!StringUtil.isStringNotNull(title)){
            return WebResult.fail("文章标题不能为空哦!");
        }
        if(notesService.updateNotes(notes,title,identity) <= 0){
            return  WebResult.fail("保存失败!请联系站长,,,");
        }
        return WebResult.success("保存成功");
    }

    /**
     * 查询文章接口
     * @param pn
     * @param request
     * @return
     */
    @RequestMapping("/toList.do")
    @ResponseBody
    public WebResult getNotesList(@RequestParam(value = "pn",defaultValue = "1")Integer pn, HttpServletRequest request) {
        Map map = MyCookie.getCookie(request);
        List<Notes> pageinfo = notesService.QueryNotes((String)map.get(MyCookie.KEYBOARD_IDENTITY));
        PageHelper.startPage(pn,7);
        PageInfo page = new PageInfo(pageinfo,5);
        return WebResult.success().add("page",page);
    }

    /**
     * 删除笔记
     * @param id
     * @return
     */
    @RequestMapping("/delete.do")
    @ResponseBody
    public WebResult del(Integer id) throws ClientException {
        if(id <= 0 || id == null){
            throw new ClientException("未获取到笔记id");
        }
        Integer result = notesService.deleteNotes(id);
        if(result == null || result == 0){
            return WebResult.fail();
        }
        return WebResult.success();
    }

}
